#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

const int BUFFER_SIZE = 1024;
const int PORT = 8081; // 默认端口

int main() {
    // 1. 创建套接字
    int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket < 0) {
        std::cerr << "Socket creation failed" << std::endl;
        return 1;
    }

    // 2. 设置SO_REUSEADDR选项
    int opt = 1;
    if (setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
        std::cerr << "Set socket option failed" << std::endl;
        close(serverSocket);
        return 1;
    }

    // 3. 绑定地址
    sockaddr_in serverAddress;
    memset(&serverAddress, 0, sizeof(serverAddress));
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = INADDR_ANY;
    serverAddress.sin_port = htons(PORT);

    if (bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) < 0) {
        std::cerr << "Bind failed" << std::endl;
        close(serverSocket);
        return 1;
    }

    // 4. 监听连接
    if (listen(serverSocket, 5) < 0) {
        std::cerr << "Listen failed" << std::endl;
        close(serverSocket);
        return 1;
    }

    std::cout << "Server listening on port " << PORT << "..." << std::endl;

    while (true) {
        // 5. 接受客户端连接
        sockaddr_in clientAddress;
        socklen_t clientAddrLen = sizeof(clientAddress);
        memset(&clientAddress, 0, sizeof(clientAddress));
        
        int clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddress, &clientAddrLen);
        if (clientSocket < 0) {
            std::cerr << "Accept failed" << std::endl;
            continue;
        }

        char clientIP[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &(clientAddress.sin_addr), clientIP, INET_ADDRSTRLEN);
        std::cout << "Client connected: " << clientIP << ":" << ntohs(clientAddress.sin_port) << std::endl;

        // 6. 处理客户端请求
        char buffer[BUFFER_SIZE];
        while (true) {
            ssize_t bytesRead = recv(clientSocket, buffer, BUFFER_SIZE - 1, 0);
            if (bytesRead <= 0) {
                if (bytesRead == 0) {
                    std::cout << "Client disconnected" << std::endl;
                } else {
                    std::cerr << "Recv error: " << strerror(errno) << std::endl;
                }
                break;
            }

            buffer[bytesRead] = '\0';
            std::cout << "Received: " << buffer << std::endl;

            // 原样发回客户端
            if (send(clientSocket, buffer, bytesRead, 0) < 0) {
                std::cerr << "Send failed: " << strerror(errno) << std::endl;
                break;
            }
        }

        // 7. 关闭客户端套接字
        close(clientSocket);
        std::cout << "Connection closed with " << clientIP << std::endl;
    }

    // 8. 关闭服务器套接字
    close(serverSocket);
    return 0;
}